# ~*~ coding: utf-8 ~*~
# auth: haochenxiao

import requests
import socket
import os
import redis
import json
from confs.Configs import *
from alert.models import AlertHistory
from devops.models import MonitorConfig
from confs.Log import logger
redis_db = 2
redisPool = redis.ConnectionPool(host=redis_host,port=redis_port,db=redis_db,password=redis_password)
client = redis.Redis(connection_pool=redisPool)
flag = 'icbc'

def send_redis(ip,alarm,item,status):
	# 发送状态到故障自愈系统处理
	ms = {
		'IP': ip,
		'告警项': alarm,
		'自愈项': item,
		'当前状态': status
	}
	vfs = json.dumps(ms)
	client.lpush(flag, vfs)


def web_monitor_test(url,alarm,item):
	res = requests.get(url)
	status_code = res.status_code
	return status_code

def web_monitor(url,alarm,item):

	try:
		res = requests.get(url)
		status_code = res.status_code
	except:
		status_code = 500
	ip= url.split('//')[1].split(':')[0]

	try:
		#查询历史状态
		mc_object = MonitorConfig.objects.get(name=alarm)
		alert_status = mc_object.alert_status
		type = mc_object.type

		# 保存历史状态
		if status_code < 400:
			status = 'OK'
			if not alert_status == 2:
				AlertHistory.objects.create(item=alarm,type=type,status=1)
				mc_object.alert_status = 2
				mc_object.save()

		else:
			status = 'BAD'
			if not alert_status == 1:
				AlertHistory.objects.create(item=alarm, type=type, status=0)
				mc_object.alert_status = 1
				mc_object.save()
	except Exception as e:
		logger.info(e)
	send_redis(ip, alarm, item, status)

	return status_code
	

def check_port_test(ip, port, alarm, item):
	#logger.info(ip, port, alarm, item)
	# 检查socket返回值
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(2)
	result = s.connect_ex((ip, int(port)))
	return result


def check_port(ip, port, alarm, item):
	try:
		# 查询历史状态
		mc_object = MonitorConfig.objects.get(name=alarm)
		alert_status = mc_object.alert_status
		type = mc_object.type
		# 检查socket返回值
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.settimeout(2)
		result = s.connect_ex((ip, int(port)))
		if result == 0:
			status = 'OK'
			if not alert_status == 2:
				AlertHistory.objects.create(item=alarm, type=type, status=1)
				mc_object.alert_status = 2
				mc_object.save()
		else:
			status = 'BAD'
			if not alert_status == 1:
				AlertHistory.objects.create(item=alarm, type=type, status=0)
				mc_object.alert_status = 1
				mc_object.save()
	except Exception as e:
		logger.info(e)

	send_redis(ip,alarm,item,status)
	return result
